<template>
	<view class="videoDetails">
		<!-- {{videoUrl[0]}} -->
		<video id="myVideo" :controls="false" :src="videoUrl[0].url" @timeupdate="updateSubtitle" autoplay>
			<!-- <track kind="subtitles" src="https://cdn.yinhehh.cn/upload/subtitle_zh/L/ATongYiDaChe4-2-A_3-1.vtt"
				srclang="en" label="Chinese" default> -->
		</video>

		<cover-view class="subtitle">{{ currentSubtitle }}</cover-view>
		<cover-view class="btnMask">
			<cover-view v-for="(item, index) in btnList" :key="index" class="btn"
				:style="{ backgroundColor: item.color }" @click="goToOthers(item.nextStoryId)">
				{{ item.text }}</cover-view>
		</cover-view>

		<!-- <video width="320" height="240" controls>
			<source src="https://cdn.yinhehh.cn/upload/1080P/L/ATongYiDaChe4-2-A_3-1.mp4" type="video/mp4">
			<track kind="subtitles" src="https://cdn.yinhehh.cn/upload/subtitle_zh/L/ATongYiDaChe4-2-A_3-1.vtt"
				srclang="en" label="Chinese" default>
		</video> -->
		<!-- <view class="goBack" @click="goBack">返回</view> -->
		<cover-view class="goBack" @click="goBack">返回</cover-view>
	</view>
</template>

<script>
	export default {

		data() {
			return {
				videoUrl: null,
				btnList: [],
				subtitles: [], // 存储解析后的字幕数据
				currentSubtitle: '', // 当前显示的字幕文本
				response: null,
				chapterId: null
			}
		},
		methods: {
			goBack() {
				
				uni.reLaunch({
					// url: '/pages/client/games/videoDetails?id=' + id
					url: '/pages/client/games/chapterDetails?id=' + this.chapterId
				});
				//刷新页面
				window.location.reload()
			},
			// 加载并解析字幕文件
			async loadSubtitles(url) {
				try {
					await uni.request({
						url: url, // 服务器接口地址
						method: 'GET', // 请求方法
						success: (res) => {
							this.response = res.data
							// const vttText = this.response.text();
							this.subtitles = this.srtToJSON(res.data);
						},
						fail: (err) => {
							console.error(err);
						}
					});
					// const response = await fetch(url);
				} catch (error) {
					console.error('Failed to load subtitles:', error);
				}
			},
			srtToJSON(srt) {
				const srtArray = srt.split('\r\n').filter(item => item !== '' && item !== '\r');
				const subtitles = [];
				for (let i = 0; i < srtArray.length; i += 3) {
					const times = srtArray[i + 1].split(' --> ');
					console.log(times, 999)
					subtitles.push({
						start: times[0].split(':')[0] * 3600 + times[0].split(':')[1] * 60 + parseFloat(times[0]
							.split(':')[2].replace(',', '.')),
						end: times[1].split(':')[0] * 3600 + times[1].split(':')[1] * 60 + parseFloat(times[1]
							.split(':')[2].replace(',', '.')),
						text: srtArray[i + 2]
					});
				}
				console.log(subtitles, 8888);
				return subtitles;
			},
			// 解析 VTT 字幕文件内容
			parseVTT(vtt) {
				const entries = vtt.split('\n\n').slice(1);
				console.log(vtt.split('\n\n'), 6666);
				const regex = /(\d{2}:\d{2}:\d{2}.\d{3}) --> (\d{2}:\d{2}:\d{2}.\d{3})\n([\s\S]*?(?=\n\n|\n*$))/g;
				const subtitles = [];
				let match;
				console.log(regex.exec(vtt), 7777)
				while ((match = regex.exec(vtt)) !== null) {
					const start = this.timeToSeconds(match[1]);
					const end = this.timeToSeconds(match[2]);
					const text = match[3].replace(/\n/g, ' '); // 将字幕文本中的换行符替换为空格
					subtitles.push({
						start,
						end,
						text
					});
				}
				return subtitles;
			},
			// 将 SRT 时间格式转换为秒
			timeToSeconds(time) {
				const parts = time.split(':');
				const hours = parseInt(parts[0], 10);
				const minutes = parseInt(parts[1], 10);
				const seconds = parseFloat(parts[2].replace(',', '.')); // VTT 使用 '.' 作为小数点
				return hours * 3600 + minutes * 60 + seconds;
			},
			// 根据视频当前时间更新字幕
			updateSubtitle(event) {
				const currentTime = event.target.currentTime;
				// console.log(this.subtitles, 1111);
				// console.log(currentTime, 222);
				const subtitle = this.subtitles.find(s => currentTime >= s.start && currentTime <= s.end);
				// console.log(subtitle, 333);
				this.currentSubtitle = subtitle ? subtitle.text : '';
			},
			goToOthers(id) {
				uni.navigateTo({
					url: '/pages/client/games/videoDetails?id=' + id + '&chapterId=' + this.chapterId
				});
				window.location.reload()
			},
			// goTo(id){
			// 	uni.navigateTo({
			// 		url: '/pages/client/games/videoDetails?id='+id
			// 	});
			// },
			getVideoInfo(id) {
				uni.request({
					url: this.configs.gameUrl + '/play/mFile/list',
					method: 'GET',
					header: {
						'X-Access-Token': this.configs.userToken // 在header中添加token
					},
					data: {
						resourceId: id,
						userId: this.configs.userId
					},
					success: data => {
						//resourceId视频资源ID
						this.videoUrl = data.data.result.records
						this.loadSubtitles(data.data.result.records[3].url);
					},
					fail: (data, code) => {}
				});
			},
			getBtn(id) {
				uni.request({
					url: this.configs.gameUrl + '/play/mButton/list',
					method: 'GET',
					header: {
						'X-Access-Token': this.configs.userToken // 在header中添加token
					},
					data: {
						storyId: id,
						userId: this.configs.userId
					},
					success: data => {
						//resourceId视频资源ID
						this.btnList = data.data.result.records
					},
					fail: (data, code) => {}
				});
			}
		},

		onLoad(option) {
			this.chapterId = option.chapterId
			this.getVideoInfo(option.id)
			this.getBtn(option.id)
		},
		mounted() {
			// this.loadSubtitles('https://cdn.yinhehh.cn/upload/subtitle_zh/L/ATongYiDaChe4-2-A_3-1.vtt');
		},
	}
</script>

<style lang="less">
	.videoDetails {
		width: 100%;
		height: 100%;
		position: relative;

		.goBack {
			position: absolute;
			top: 10rpx;
			right: 10rpx;
			width: 100rpx;
			height: 24rpx;
			//粉色背景
			background: #F8879C;
			border-radius: 12rpx;
			text-align: center;
			line-height: 24rpx;
			color: #fff;
			font-size: 14rpx;
		}

		video {
			width: 100%;
			height: 100vh;
		}

		.subtitle {
			position: absolute;
			bottom: 20rpx;
			width: 100%;
			text-align: center;
			color: white;
			font-size: 16px;
		}

		.btnMask {
			position: absolute;
			bottom: 46rpx;
			width: 100%;
			display: flex; 
			justify-content: space-around;
			z-index: 20;

			.btn {
				// width: 25%;
				height: 30rpx;
				line-height: 30rpx;
				text-align: center;
				background-color: #000;
				color: #fff;
				font-size: 14rpx;
				padding: 0 20rpx;
				border-radius: 15rpx;
				animation: identifier 1s infinite;
				min-width: 80rpx;
			}

			@keyframes identifier {
				0% {
					transform: scale(1);
				}

				50% {
					transform: scale(1.1);
				}

				100% {
					transform: scale(1);
				}

			}
		}
	}
</style>